package com.envmonitor.application.service;

import com.envmonitor.domain.model.Device;
import com.envmonitor.domain.model.EnvironmentData;
import com.envmonitor.domain.service.DeviceService;
import com.envmonitor.domain.service.EnvironmentDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class EnvironmentDataApplicationService {
    
    private final EnvironmentDataService environmentDataService;
    private final DeviceService deviceService;
    
    public List<EnvironmentData> getAllData() {
        return environmentDataService.getAllData();
    }
    
    public Optional<EnvironmentData> getDataById(Long id) {
        return environmentDataService.getDataById(id);
    }
    
    public List<EnvironmentData> getDataByDeviceId(Long deviceId) {
        return environmentDataService.getDataByDeviceId(deviceId);
    }
    
    @Transactional
    public Optional<EnvironmentData> createData(EnvironmentData data, Long deviceId) {
        Optional<Device> deviceOpt = deviceService.getDeviceById(deviceId);
        if (deviceOpt.isPresent()) {
            Device device = deviceOpt.get();
            data.setDevice(device);
            data.setRecordedAt(LocalDateTime.now());
            return Optional.of(environmentDataService.saveData(data));
        }
        return Optional.empty();
    }
    
    @Transactional
    public Optional<EnvironmentData> updateData(Long id, EnvironmentData dataDetails) {
        Optional<EnvironmentData> dataOpt = environmentDataService.getDataById(id);
        if (dataOpt.isPresent()) {
            EnvironmentData data = dataOpt.get();
            data.setTemperature(dataDetails.getTemperature());
            data.setHumidity(dataDetails.getHumidity());
            data.setEnergyConsumption(dataDetails.getEnergyConsumption());
            return Optional.of(environmentDataService.saveData(data));
        }
        return Optional.empty();
    }
    
    @Transactional
    public void deleteData(Long id) {
        environmentDataService.deleteData(id);
    }
    
    public List<EnvironmentData> getDataByTimeRange(LocalDateTime start, LocalDateTime end) {
        return environmentDataService.getDataByTimeRange(start, end);
    }
    
    public List<EnvironmentData> getHighTemperatureAlerts(Double threshold) {
        return environmentDataService.getDataByTemperatureThreshold(threshold);
    }
    
    public List<EnvironmentData> getHighHumidityAlerts(Double threshold) {
        return environmentDataService.getDataByHumidityThreshold(threshold);
    }
    
    public List<EnvironmentData> getHighEnergyConsumptionAlerts(Double threshold) {
        return environmentDataService.getDataByEnergyConsumptionThreshold(threshold);
    }
}